#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QTimer>
#include <QComboBox>
#include <QListWidgetItem>
#include <QMenu>
#include <QPropertyAnimation>

// 格式化时间（毫秒 → 00:00:00）
QString formatTime(int64_t ms) {
    int seconds = ms / 1000;
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    int secs = seconds % 60;
    return QString("%1:%2:%3")
        .arg(hours, 2, 10, QChar('0'))
        .arg(minutes, 2, 10, QChar('0'))
        .arg(secs, 2, 10, QChar('0'));
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_decodeThread(new DecodeThread(this))
    , m_isPlaying(false)
    , m_isSliderPressed(false)
    , m_isUserSeeking(false)
    , m_totalDurationMs(0)
    , m_currentPlaylistIndex(-1)
    , m_isPlaylistVisible(true)
{
    ui->setupUi(this);
    
    // 连接解码线程信号到 UI 中的 videoWidget
    connect(m_decodeThread, &DecodeThread::frameDecoded, 
            ui->videoWidget, &VideoWidget::updateImage);
    connect(m_decodeThread, &DecodeThread::durationChanged, 
            this, &MainWindow::onDurationChanged);
    connect(m_decodeThread, &DecodeThread::positionChanged, 
            this, &MainWindow::onPositionChanged);
    connect(m_decodeThread, &DecodeThread::playbackFinished, 
            this, &MainWindow::onPlaybackFinished);
    connect(m_decodeThread, &DecodeThread::errorOccurred, 
            this, &MainWindow::onErrorOccurred);
    
    // 初始化音量滑块
    ui->volumeSlider->setRange(0, 100);      // 音量范围 0-100
    ui->volumeSlider->setValue(100);         // 默认最大音量
    ui->volumeSlider->setOrientation(Qt::Horizontal);
    connect(ui->volumeSlider, &QSlider::valueChanged, 
            this, &MainWindow::on_volumeSlider_valueChanged);
    
    // 初始化倍速下拉框（如果UI中有speedComboBox）
    if (ui->speedComboBox) {
        ui->speedComboBox->clear();
        ui->speedComboBox->addItem("0.5x", 0.5);
        ui->speedComboBox->addItem("0.75x", 0.75);
        ui->speedComboBox->addItem("1.0x (正常)", 1.0);
        ui->speedComboBox->addItem("1.25x", 1.25);
        ui->speedComboBox->addItem("1.5x", 1.5);
        ui->speedComboBox->addItem("2.0x", 2.0);
        ui->speedComboBox->setCurrentIndex(2);  // 默认1.0x
        connect(ui->speedComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &MainWindow::on_speedComboBox_currentIndexChanged);
    }
    
    // 初始化播放列表
    ui->playlist->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->playlist, &QListWidget::customContextMenuRequested,
            this, &MainWindow::onPlaylistContextMenu);
    connect(ui->playlist, &QListWidget::itemDoubleClicked,
            this, &MainWindow::on_playlist_itemDoubleClicked);
    
    // 连接播放列表切换按钮
    connect(ui->togglePlaylistButton, &QPushButton::clicked,
            this, &MainWindow::togglePlaylist);
    
    // 设置全局工具提示样式
    qApp->setStyleSheet(qApp->styleSheet() + 
        "QToolTip { "
        "   background-color: #2a2a2a; "
        "   color: white; "
        "   border: 1px solid #555; "
        "   border-radius: 4px; "
        "   padding: 5px; "
        "   font-size: 12px; "
        "}");
    
    // 初始状态显示第0页（初始页面）
    switchToIdlePage();
    
    setWindowTitle("视频播放器");
    
    qDebug() << "[MainWindow] 窗口初始化完成";
}

MainWindow::~MainWindow()
{
    m_decodeThread->stop();
    m_decodeThread->wait();
    delete ui;
    qDebug() << "[MainWindow] 窗口销毁";
}

// ==================== 页面切换 ====================
void MainWindow::switchToIdlePage()
{
    ui->stackedWidget->setCurrentIndex(0);  // 切换到第0页（初始页面）
    setWindowTitle("视频播放器");
    qDebug() << "[MainWindow] 切换到初始页面";
}

void MainWindow::switchToPlayingPage()
{
    ui->stackedWidget->setCurrentIndex(1);  // 切换到第1页（播放页面）
    qDebug() << "[MainWindow] 切换到播放页面";
}

// ==================== UI按钮槽函数 ====================
void MainWindow::on_openButton_clicked()
{
    qDebug() << "[MainWindow] 点击打开文件按钮";
    
    // 支持多选文件
    QStringList videoPaths = QFileDialog::getOpenFileNames(
        this, "选择视频文件（可多选）", "", "视频文件 (*.mp4 *.avi *.mkv *.flv *.mov *.wmv)");
    
    if (videoPaths.isEmpty()) {
        qDebug() << "[MainWindow] 用户取消选择";
        return;
    }
    
    qDebug() << "[MainWindow] 选择了" << videoPaths.count() << "个视频";
    
    // 停止当前播放
    m_decodeThread->stop();
    m_decodeThread->wait();
    
    // 添加所有视频到播放列表
    for (const QString& path : videoPaths) {
        addVideoToPlaylist(path);
    }
    
    // 自动播放第一个视频
    if (ui->playlist->count() > 0) {
        playVideoByIndex(0);
    }
}

void MainWindow::on_playUrlButton_clicked()
{
    qDebug() << "[MainWindow] 点击播放网络视频按钮";
    
    QString url = ui->urlInput->text().trimmed();
    
    if (url.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入网络视频地址");
        return;
    }
    
    // 验证是否是网络地址
    if (!url.startsWith("http://") && 
        !url.startsWith("https://") && 
        !url.startsWith("rtsp://") && 
        !url.startsWith("rtmp://")) {
        QMessageBox::warning(this, "错误", 
            "请输入有效的网络地址\n\n支持的协议：\n"
            "• HTTP/HTTPS（普通视频文件）\n"
            "• RTSP（监控摄像头）\n"
            "• RTMP（直播流）\n"
            "• HLS (.m3u8 直播/点播）");
        return;
    }
    
    // 停止当前播放
    m_decodeThread->stop();
    m_decodeThread->wait();
    
    qDebug() << "[MainWindow] 尝试打开网络视频：" << url;
    
    // 打开网络视频
    if (m_decodeThread->openVideo(url)) {
        m_currentVideoPath = url;
        m_currentPlaylistIndex = -1;  // 网络视频不在播放列表中
        
        setWindowTitle("视频播放器 - 网络视频");
        
        // 切换到播放页面
        switchToPlayingPage();
        
        // 清空播放列表高亮（网络视频不在列表中）
        ui->playlist->clearSelection();
        
        // 开始播放
        m_decodeThread->play();
        m_isPlaying = true;
        ui->playButton->setText("⏸");
        
        qDebug() << "[MainWindow] 网络视频播放成功";
    } else {
        QMessageBox::warning(this, "错误", 
            "无法打开网络视频\n\n可能的原因：\n"
            "• 网络连接失败\n"
            "• 视频地址无效\n"
            "• 视频格式不支持\n"
            "• 服务器无响应");
        qDebug() << "[MainWindow] 网络视频打开失败";
    }
}

void MainWindow::on_playButton_clicked()
{
    if (m_isPlaying) {
        m_decodeThread->pause();
        m_isPlaying = false;
        ui->playButton->setText("▶");
        qDebug() << "[MainWindow] 暂停播放";
    } else {
        m_decodeThread->play();
        m_isPlaying = true;
        ui->playButton->setText("⏸");
        qDebug() << "[MainWindow] 继续播放";
    }
}

void MainWindow::on_progressSlider_sliderPressed()
{
    m_isSliderPressed = true;
    m_isUserSeeking = true;  // 标记用户正在操作
    qDebug() << "[MainWindow] 用户按下进度条";
}

void MainWindow::on_progressSlider_sliderReleased()
{
    m_isSliderPressed = false;
    
    // 用户释放进度条时，跳转到对应位置
    int64_t seekPosition = ui->progressSlider->value();
    m_decodeThread->seek(seekPosition);
    
    qDebug() << "[MainWindow] 用户释放进度条，跳转到：" << seekPosition << "ms";
    
    // 延迟解除 seeking 标志，给解码线程一点时间完成 seek
    QTimer::singleShot(100, this, [this]() {
        m_isUserSeeking = false;
        qDebug() << "[MainWindow] 解除 seeking 标志";
    });
}

void MainWindow::on_progressSlider_valueChanged(int value)
{
    // 检查是否是用户手动操作（拖动或点击）
    bool isUserAction = ui->progressSlider->isSliderDown() || m_isSliderPressed;
    
    if (isUserAction) {
        // 用户正在操作，更新时间显示
        QString currentTime = formatTime(value);
        QString totalTime = formatTime(m_totalDurationMs);
        ui->timeLabel->setText(currentTime + " / " + totalTime);
        
        // 如果是点击（不是拖动），立即执行 seek
        if (!m_isSliderPressed) {
            m_isUserSeeking = true;
            m_decodeThread->seek(value);
            qDebug() << "[MainWindow] 用户点击进度条，跳转到：" << value << "ms";
            
            // 延迟解除 seeking 标志
            QTimer::singleShot(100, this, [this]() {
                m_isUserSeeking = false;
                qDebug() << "[MainWindow] 解除 seeking 标志";
            });
        }
    }
}

void MainWindow::on_volumeSlider_valueChanged(int value)
{
    // 设置音量（0-100）
    m_decodeThread->setVolume(value);
}

void MainWindow::on_speedComboBox_currentIndexChanged(int index)
{
    if (!ui->speedComboBox) return;
    
    // 获取下拉框中存储的倍速值
    double speed = ui->speedComboBox->itemData(index).toDouble();
    m_decodeThread->setPlaybackSpeed(speed);
    
    qDebug() << "[MainWindow] 设置播放倍速：" << speed << "x";
}

// ==================== 解码线程信号槽 ====================
void MainWindow::onDurationChanged(int64_t durationMs)
{
    m_totalDurationMs = durationMs;
    ui->progressSlider->setMaximum(durationMs);
    
    QString totalTime = formatTime(durationMs);
    ui->timeLabel->setText("00:00:00 / " + totalTime);
    
    // 显示解码器信息在窗口标题
    QString decoderInfo = m_decodeThread->getDecoder()->getDecoderInfo();
    QString fileName = QFileInfo(m_currentVideoPath).fileName();
    setWindowTitle("视频播放器 - " + fileName + " [" + decoderInfo + "]");
    
    qDebug() << "[MainWindow] 视频时长：" << totalTime;
    qDebug() << "[MainWindow] 解码模式：" << decoderInfo;
}

void MainWindow::onPositionChanged(int64_t positionMs)
{
    // 只有在用户没有操作进度条时才更新
    if (!m_isSliderPressed && !m_isUserSeeking) {
        ui->progressSlider->setValue(positionMs);
        
        QString currentTime = formatTime(positionMs);
        QString totalTime = formatTime(m_totalDurationMs);
        ui->timeLabel->setText(currentTime + " / " + totalTime);
    }
}

void MainWindow::onPlaybackFinished()
{
    qDebug() << "[MainWindow] 播放结束";
    
    // 自动播放下一个视频
    playNextVideo();
    
    // 如果没有下一个视频了，更新播放按钮状态
    if (!m_isPlaying) {
        ui->playButton->setText("▶");
        qDebug() << "[MainWindow] 播放列表已全部播放完毕";
    }
}

void MainWindow::onErrorOccurred(QString error)
{
    QMessageBox::critical(this, "错误", error);
    qDebug() << "[MainWindow] 发生错误：" << error;
}

// ==================== 播放列表功能实现 ====================

void MainWindow::addVideoToPlaylist(const QString& filePath)
{
    // 检查是否已存在
    for (int i = 0; i < ui->playlist->count(); ++i) {
        QListWidgetItem* item = ui->playlist->item(i);
        if (item->data(Qt::UserRole).toString() == filePath) {
            qDebug() << "[Playlist] 视频已存在，跳过：" << filePath;
            return;
        }
    }
    
    // 创建列表项
    QFileInfo fileInfo(filePath);
    QListWidgetItem* item = new QListWidgetItem(fileInfo.fileName());
    item->setData(Qt::UserRole, filePath);  // 存储完整路径
    item->setToolTip(filePath);             // 鼠标悬停显示完整路径
    
    ui->playlist->addItem(item);
    qDebug() << "[Playlist] 添加视频：" << fileInfo.fileName();
}

void MainWindow::playVideoByIndex(int index)
{
    if (index < 0 || index >= ui->playlist->count()) {
        qDebug() << "[Playlist] 无效的索引：" << index;
        return;
    }
    
    // 获取视频路径
    QListWidgetItem* item = ui->playlist->item(index);
    QString videoPath = item->data(Qt::UserRole).toString();
    
    qDebug() << "[Playlist] 播放索引" << index << "：" << videoPath;
    
    // 停止当前播放
    m_decodeThread->stop();
    m_decodeThread->wait();
    
    // 打开新视频
    if (m_decodeThread->openVideo(videoPath)) {
        m_currentVideoPath = videoPath;
        m_currentPlaylistIndex = index;
        
        setWindowTitle("视频播放器 - " + QFileInfo(videoPath).fileName());
        
        // 切换到播放页面
        switchToPlayingPage();
        
        // 更新播放列表高亮
        updatePlaylistHighlight();
        
        // 开始播放
        m_decodeThread->play();
        m_isPlaying = true;
        ui->playButton->setText("⏸");
        
        qDebug() << "[Playlist] 视频打开成功，开始播放";
    } else {
        QMessageBox::warning(this, "错误", "无法打开视频：" + videoPath);
        qDebug() << "[Playlist] 视频打开失败：" << videoPath;
    }
}

void MainWindow::playNextVideo()
{
    if (ui->playlist->count() == 0) {
        qDebug() << "[Playlist] 播放列表为空";
        m_isPlaying = false;
        return;
    }
    
    int nextIndex = m_currentPlaylistIndex + 1;
    
    if (nextIndex < ui->playlist->count()) {
        qDebug() << "[Playlist] 播放下一个视频，索引：" << nextIndex;
        playVideoByIndex(nextIndex);
    } else {
        qDebug() << "[Playlist] 已到达播放列表末尾";
        m_isPlaying = false;
        m_currentPlaylistIndex = -1;
    }
}

void MainWindow::updatePlaylistHighlight()
{
    // 清除所有选中状态
    ui->playlist->clearSelection();
    
    // 高亮当前播放的项
    if (m_currentPlaylistIndex >= 0 && m_currentPlaylistIndex < ui->playlist->count()) {
        QListWidgetItem* item = ui->playlist->item(m_currentPlaylistIndex);
        item->setSelected(true);
        ui->playlist->scrollToItem(item);  // 滚动到当前项
        
        qDebug() << "[Playlist] 高亮索引：" << m_currentPlaylistIndex;
    }
}

void MainWindow::on_playlist_itemDoubleClicked(QListWidgetItem* item)
{
    int index = ui->playlist->row(item);
    qDebug() << "[Playlist] 双击播放，索引：" << index;
    
    // 如果双击的是当前正在播放的视频，跳转到开头重新播放
    if (index == m_currentPlaylistIndex && m_isPlaying) {
        qDebug() << "[Playlist] 当前视频，跳转到开头重新播放";
        m_decodeThread->seek(0);  // 跳转到开头
        return;
    }
    
    playVideoByIndex(index);
}

void MainWindow::onPlaylistContextMenu(const QPoint& pos)
{
    QListWidgetItem* item = ui->playlist->itemAt(pos);
    
    QMenu menu(this);
    
    if (item) {
        // 有选中项的菜单
        QAction* playAction = menu.addAction("▶️ 播放");
        QAction* removeAction = menu.addAction("🗑️ 移除");
        menu.addSeparator();
        QAction* clearAction = menu.addAction("🧹 清空列表");
        
        QAction* selectedAction = menu.exec(ui->playlist->mapToGlobal(pos));
        
        if (selectedAction == playAction) {
            // 播放选中的视频
            int index = ui->playlist->row(item);
            
            // 如果是当前正在播放的视频，跳转到开头
            if (index == m_currentPlaylistIndex && m_isPlaying) {
                qDebug() << "[Playlist] 当前视频，跳转到开头重新播放";
                m_decodeThread->seek(0);
            } else {
                playVideoByIndex(index);
            }
        } 
        else if (selectedAction == removeAction) {
            // 移除选中的视频
            int index = ui->playlist->row(item);
            qDebug() << "[Playlist] 移除索引：" << index;
            
            // 如果移除的是当前播放的视频，停止播放
            if (index == m_currentPlaylistIndex) {
                m_decodeThread->stop();
                m_decodeThread->wait();
                m_isPlaying = false;
                ui->playButton->setText("▶");
                m_currentPlaylistIndex = -1;
            } 
            else if (index < m_currentPlaylistIndex) {
                // 如果移除的在当前播放之前，索引需要-1
                m_currentPlaylistIndex--;
            }
            
            delete ui->playlist->takeItem(index);
        } 
        else if (selectedAction == clearAction) {
            // 清空播放列表
            qDebug() << "[Playlist] 清空播放列表";
            
            m_decodeThread->stop();
            m_decodeThread->wait();
            ui->playlist->clear();
            m_isPlaying = false;
            ui->playButton->setText("▶");
            m_currentPlaylistIndex = -1;
            switchToIdlePage();
        }
    } 
    else {
        // 空白区域右键，只显示清空选项
        QAction* clearAction = menu.addAction("🧹 清空列表");
        
        QAction* selectedAction = menu.exec(ui->playlist->mapToGlobal(pos));
        
        if (selectedAction == clearAction && ui->playlist->count() > 0) {
            qDebug() << "[Playlist] 清空播放列表";
            
            m_decodeThread->stop();
            m_decodeThread->wait();
            ui->playlist->clear();
            m_isPlaying = false;
            ui->playButton->setText("▶");
            m_currentPlaylistIndex = -1;
            switchToIdlePage();
        }
    }
}

// 切换播放列表显示/隐藏
void MainWindow::togglePlaylist()
{
    m_isPlaylistVisible = !m_isPlaylistVisible;
    
    // 创建动画
    QPropertyAnimation* animation = new QPropertyAnimation(ui->playlistWidget, "maximumWidth");
    animation->setDuration(300);  // 动画时长 300ms
    animation->setEasingCurve(QEasingCurve::InOutCubic);  // 平滑曲线
    
    if (m_isPlaylistVisible) {
        // 显示播放列表
        animation->setStartValue(0);
        animation->setEndValue(300);  // 恢复原宽度
        ui->playlistWidget->setMinimumWidth(250);
        ui->togglePlaylistButton->setText("▶");  // 向右箭头表示可收起
        ui->togglePlaylistButton->setToolTip("收起播放列表");
        qDebug() << "[MainWindow] 显示播放列表";
    } else {
        // 隐藏播放列表
        animation->setStartValue(ui->playlistWidget->width());
        animation->setEndValue(0);
        ui->playlistWidget->setMinimumWidth(0);
        ui->togglePlaylistButton->setText("◀");  // 向左箭头表示可展开
        ui->togglePlaylistButton->setToolTip("展开播放列表");
        qDebug() << "[MainWindow] 隐藏播放列表";
    }
    
    animation->start(QAbstractAnimation::DeleteWhenStopped);  // 动画完成后自动删除
}

